package com.yt.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
import com.yt.sys.mapper.PaymentOrderMapper;
import com.yt.sys.models.entity.PaymentOrder;
import com.yt.sys.models.service.IPaymentOrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 支付订单服务实现类
 */
@DubboService
@Service
public class PaymentOrderServiceImpl extends ServiceImpl<PaymentOrderMapper, PaymentOrder> implements IPaymentOrderService {
    
    @Override
    public PaymentOrder getPaymentOrderByOrderNo(String orderNo) {
        EntityWrapper<PaymentOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        return this.selectOne(wrapper);
    }
    
    @Override
    public String createPaymentOrder(Long userId, Double amount) {
        // 生成订单号：使用时间戳+用户ID后四位的方式确保唯一性且为纯数字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        String userIdSuffix = String.format("%04d", userId % 10000); // 用户ID后四位，不足补0
        String orderNo = timestamp + userIdSuffix;
        
        // 创建支付订单
        PaymentOrder paymentOrder = new PaymentOrder();
        paymentOrder.setOrderNo(orderNo);
        paymentOrder.setUserId(userId);
        paymentOrder.setAmount(amount);
        paymentOrder.setStatus(0); // 待支付状态
        paymentOrder.setCreateTime(new Date());
        paymentOrder.setUpdateTime(new Date());
        
        // 保存到数据库
        this.insert(paymentOrder);
        
        return orderNo;
    }
    
    @Override
    public boolean updatePaymentOrderStatus(String orderNo, Integer status) {
        PaymentOrder paymentOrder = this.getPaymentOrderByOrderNo(orderNo);
        if (paymentOrder != null) {
            paymentOrder.setStatus(status);
            paymentOrder.setUpdateTime(new Date());
            return this.updateById(paymentOrder);
        }
        return false;
    }
}